<template>
  <div class="task-panel" :class="taskPanelClasses">
    <!-- 面板头部 -->
    <header class="panel-header">
      <div class="header-left">
        <h3 class="panel-title">
          <el-icon><List /></el-icon>
          任务管理
        </h3>
        <el-badge v-if="taskStore.hasTasks" :value="taskStore.currentTasks.length" class="task-count-badge" />
      </div>
      
      <div class="header-actions">
        <el-tooltip content="刷新任务">
          <el-button type="text" icon="Refresh" @click="refreshTasks" class="action-btn" />
        </el-tooltip>
        
        <el-tooltip content="导出任务">
          <el-button type="text" icon="Download" @click="exportTasks" class="action-btn" />
        </el-tooltip>
        
        <el-dropdown @command="handleMenuAction" trigger="click">
          <el-button type="text" icon="MoreFilled" class="action-btn" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="clear" icon="Delete">清空任务</el-dropdown-item>
              <el-dropdown-item command="import" icon="Upload">导入任务</el-dropdown-item>
              <el-dropdown-item command="settings" icon="Setting" divided>任务设置</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 任务统计 -->
    <div v-if="taskStore.hasTasks" class="task-stats">
      <div class="stat-item">
        <span class="stat-label">总计</span>
        <span class="stat-value">{{ taskStore.currentTasks.length }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">待执行</span>
        <span class="stat-value pending">{{ taskStore.pendingTasks.length }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">进行中</span>
        <span class="stat-value progress">{{ taskStore.inProgressTasks.length }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">已完成</span>
        <span class="stat-value completed">{{ taskStore.completedTasks.length }}</span>
      </div>
    </div>

    <!-- 任务列表区域 -->
    <div class="task-content">
      <!-- 有任务时的内容 -->
      <div v-if="taskStore.hasTasks" class="task-list-container">
        <!-- 任务过滤器 -->
        <div class="task-filters">
          <el-radio-group v-model="activeFilter" size="small" @change="handleFilterChange">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="pending">待执行</el-radio-button>
            <el-radio-button label="progress">进行中</el-radio-button>
            <el-radio-button label="completed">已完成</el-radio-button>
          </el-radio-group>
          
          <el-button-group class="view-controls">
            <el-tooltip content="列表视图">
              <el-button
                :type="viewMode === 'list' ? 'primary' : 'default'"
                icon="List"
                @click="viewMode = 'list'"
                size="small"
              />
            </el-tooltip>
            <el-tooltip content="卡片视图">
              <el-button
                :type="viewMode === 'card' ? 'primary' : 'default'"
                icon="Grid"
                @click="viewMode = 'card'"
                size="small"
              />
            </el-tooltip>
          </el-button-group>
        </div>

        <!-- 任务列表 -->
        <div class="task-list" :class="`task-list--${viewMode}`">
          <draggable
            v-model="filteredTasks"
            group="tasks"
            @end="handleTaskReorder"
            :disabled="!canReorder"
            item-key="id"
            class="task-draggable"
          >
            <template #item="{ element: task }">
              <TaskCard
                :key="task.id"
                :task="task"
                :selected="taskStore.selectedTaskIds.has(task.id)"
                :view-mode="viewMode"
                :show-dependencies="showDependencies"
                :allow-modification="allowModification"
                @select="handleTaskSelect"
                @action="handleTaskAction"
                @edit="handleTaskEdit"
                @delete="handleTaskDelete"
              />
            </template>
          </draggable>
        </div>

        <!-- 任务操作栏 -->
        <div v-if="hasSelectedTasks" class="task-actions">
          <div class="selected-info">
            已选择 {{ selectedTaskCount }} 个任务
          </div>
          <div class="action-buttons">
            <el-button size="small" @click="taskStore.deselectAllTasks">取消选择</el-button>
            <el-button type="warning" size="small" @click="handleBatchEdit">批量编辑</el-button>
            <el-button type="danger" size="small" @click="handleBatchDelete">批量删除</el-button>
          </div>
        </div>
      </div>

      <!-- 无任务时的空状态 -->
      <div v-else class="empty-state">
        <div class="empty-content">
          <div class="empty-icon">
            <el-icon><List /></el-icon>
          </div>
          <h4 class="empty-title">暂无任务</h4>
          <p class="empty-description">
            当您提出复杂问题时，AI会自动将其分解为多个任务。
          </p>
          <div class="empty-actions">
            <el-button type="primary" @click="createSampleTasks">
              创建示例任务
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 执行控制区域 -->
    <div v-if="taskStore.hasTasks" class="execution-controls">
      <div class="control-buttons">
        <el-button
          v-if="taskStore.canExecute"
          type="primary"
          :icon="Play"
          @click="confirmExecution"
          class="execute-btn"
        >
          确认执行
        </el-button>
        
        <el-button
          v-if="taskStore.isExecuting"
          type="warning"
          :icon="VideoPause"
          @click="pauseExecution"
        >
          暂停执行
        </el-button>
        
        <el-button
          v-if="taskStore.isExecuting"
          type="danger"
          :icon="VideoStop"
          @click="cancelExecution"
        >
          停止执行
        </el-button>
        
        <el-button
          v-if="showModifyButton"
          type="info"
          :icon="Edit"
          @click="startModification"
        >
          修改任务
        </el-button>
      </div>
      
      <!-- 执行进度 -->
      <div v-if="taskStore.isExecuting" class="execution-progress">
        <div class="progress-info">
          <span class="progress-text">执行进度: {{ taskStore.executionProgress }}%</span>
          <span class="progress-time">{{ executionTimeText }}</span>
        </div>
        <el-progress
          :percentage="taskStore.executionProgress"
          :status="progressStatus"
          :stroke-width="6"
        />
      </div>
    </div>

    <!-- 任务修改对话框 -->
    <el-dialog
      v-model="taskStore.modificationDialog.visible"
      title="任务修改"
      width="60%"
      :before-close="handleModificationClose"
    >
      <TaskModification
        :task-id="taskStore.modificationDialog.taskId"
        :modification-type="taskStore.modificationDialog.type"
        @confirm="handleModificationConfirm"
        @cancel="taskStore.cancelModification"
      />
    </el-dialog>

    <!-- 文件上传 -->
    <input
      ref="fileInputRef"
      type="file"
      accept=".json"
      style="display: none"
      @change="handleFileImport"
    />
  </div>
</template>

<script setup lang="ts">
import { useTaskStore } from '@/stores/task'
import { useUIStore } from '@/stores/ui'
import TaskCard from './TaskCard.vue'
import TaskModification from './TaskModification.vue'
import draggable from 'vuedraggable'
import type { TaskModification as TaskModificationType } from '@/types'

const taskStore = useTaskStore()
const uiStore = useUIStore()

// Props
interface Props {
  allowModification?: boolean
  showDependencies?: boolean
  autoRefresh?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  allowModification: true,
  showDependencies: true,
  autoRefresh: true
})

// 状态
const activeFilter = ref<'all' | 'pending' | 'progress' | 'completed'>('all')
const viewMode = ref<'list' | 'card'>('card')
const fileInputRef = ref<HTMLInputElement>()
const executionStartTime = ref<Date | null>(null)

// 计算属性
const taskPanelClasses = computed(() => ({
  'task-panel': true,
  'task-panel--executing': taskStore.isExecuting,
  'task-panel--empty': !taskStore.hasTasks
}))

const filteredTasks = computed({
  get() {
    let tasks = [...taskStore.currentTasks]
    
    switch (activeFilter.value) {
      case 'pending':
        tasks = taskStore.pendingTasks
        break
      case 'progress':
        tasks = taskStore.inProgressTasks
        break
      case 'completed':
        tasks = taskStore.completedTasks
        break
      default:
        tasks = taskStore.currentTasks
    }
    
    return tasks
  },
  set(newTasks) {
    // 处理拖拽重排序
    const newOrder = newTasks.map(task => task.id)
    taskStore.reorderTasks(newOrder)
  }
})

const hasSelectedTasks = computed(() => taskStore.selectedTaskIds.size > 0)

const selectedTaskCount = computed(() => taskStore.selectedTaskIds.size)

const canReorder = computed(() => 
  props.allowModification && 
  !taskStore.isExecuting && 
  activeFilter.value === 'all'
)

const showModifyButton = computed(() =>
  props.allowModification &&
  taskStore.hasTasks &&
  !taskStore.isExecuting
)

const progressStatus = computed(() => {
  if (taskStore.executionProgress === 100) return 'success'
  if (taskStore.failedTasks.length > 0) return 'exception'
  return undefined
})

const executionTimeText = computed(() => {
  if (!executionStartTime.value) return ''
  
  const elapsed = Date.now() - executionStartTime.value.getTime()
  const minutes = Math.floor(elapsed / 60000)
  const seconds = Math.floor((elapsed % 60000) / 1000)
  
  return `${minutes}:${seconds.toString().padStart(2, '0')}`
})

// 方法
const refreshTasks = () => {
  // 刷新任务列表
  uiStore.showSuccess('任务列表已刷新')
}

const exportTasks = () => {
  try {
    const taskData = taskStore.exportTasks()
    if (taskData) {
      const blob = new Blob([JSON.stringify(taskData, null, 2)], {
        type: 'application/json'
      })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `tasks-${taskData.sessionId}.json`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      
      uiStore.showSuccess('任务已导出')
    }
  } catch (error) {
    console.error('Export failed:', error)
    uiStore.showError('导出失败')
  }
}

const handleMenuAction = (command: string) => {
  switch (command) {
    case 'clear':
      handleClearTasks()
      break
    case 'import':
      triggerFileImport()
      break
    case 'settings':
      // 打开任务设置
      break
  }
}

const handleClearTasks = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有任务吗？此操作不可撤销。',
      '确认清空',
      {
        confirmButtonText: '清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    taskStore.clearTasks()
    uiStore.showSuccess('任务已清空')
  } catch {
    // 用户取消
  }
}

const triggerFileImport = () => {
  fileInputRef.value?.click()
}

const handleFileImport = (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return
  
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = JSON.parse(e.target?.result as string)
      const success = taskStore.importTasks(data)
      
      if (success) {
        uiStore.showSuccess('任务导入成功')
      } else {
        uiStore.showError('任务导入失败')
      }
    } catch (error) {
      console.error('Import failed:', error)
      uiStore.showError('文件格式错误')
    }
  }
  reader.readAsText(file)
}

const handleFilterChange = (filter: string) => {
  activeFilter.value = filter as typeof activeFilter.value
}

const handleTaskReorder = () => {
  uiStore.showSuccess('任务顺序已更新')
}

const handleTaskSelect = (taskId: string, selected: boolean) => {
  if (selected) {
    taskStore.selectTask(taskId)
  } else {
    taskStore.deselectTask(taskId)
  }
}

const handleTaskAction = (action: string, taskId: string) => {
  switch (action) {
    case 'view':
      // 查看任务详情
      break
    case 'execute':
      // 单独执行任务
      break
    case 'duplicate':
      // 复制任务
      break
  }
}

const handleTaskEdit = (taskId: string) => {
  taskStore.startModification(taskId, 'modify')
}

const handleTaskDelete = async (taskId: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个任务吗？',
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    taskStore.deleteTask(taskId)
    uiStore.showSuccess('任务已删除')
  } catch {
    // 用户取消
  }
}

const handleBatchEdit = () => {
  if (selectedTaskCount.value > 0) {
    taskStore.startModification(undefined, 'modify')
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedTaskCount.value} 个任务吗？`,
      '确认批量删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const selectedTasks = taskStore.getSelectedTasks()
    selectedTasks.forEach(task => taskStore.deleteTask(task.id))
    taskStore.deselectAllTasks()
    
    uiStore.showSuccess(`已删除 ${selectedTasks.length} 个任务`)
  } catch {
    // 用户取消
  }
}

const createSampleTasks = () => {
  // 创建示例任务用于演示
  const sampleTasks = [
    {
      description: '分析用户需求',
      type: 'ANALYSIS' as const,
      status: 'PENDING' as const,
      priority: 1,
      sequence: 1,
      dependencies: [],
      agentType: 'GENERAL_QA' as const,
      estimatedTime: 30,
      progress: 0,
      sessionId: 'demo'
    },
    {
      description: '设计解决方案',
      type: 'REASONING' as const,
      status: 'PENDING' as const,
      priority: 2,
      sequence: 2,
      dependencies: [],
      agentType: 'GENERAL_QA' as const,
      estimatedTime: 45,
      progress: 0,
      sessionId: 'demo'
    },
    {
      description: '实施计划',
      type: 'SYNTHESIS' as const,
      status: 'PENDING' as const,
      priority: 3,
      sequence: 3,
      dependencies: [],
      agentType: 'GENERAL_QA' as const,
      estimatedTime: 60,
      progress: 0,
      sessionId: 'demo'
    }
  ]
  
  taskStore.addMultipleTasks(sampleTasks)
  uiStore.showSuccess('示例任务已创建')
}

const confirmExecution = async () => {
  try {
    const success = await taskStore.confirmExecution()
    if (success) {
      executionStartTime.value = new Date()
      uiStore.showSuccess('任务执行已开始')
    }
  } catch (error) {
    console.error('Execution failed:', error)
    uiStore.showError('执行失败')
  }
}

const pauseExecution = async () => {
  try {
    const success = await taskStore.pauseExecution()
    if (success) {
      uiStore.showSuccess('任务执行已暂停')
    }
  } catch (error) {
    console.error('Pause failed:', error)
    uiStore.showError('暂停失败')
  }
}

const cancelExecution = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要停止任务执行吗？',
      '确认停止',
      {
        confirmButtonText: '停止',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const success = await taskStore.cancelExecution()
    if (success) {
      executionStartTime.value = null
      uiStore.showSuccess('任务执行已停止')
    }
  } catch {
    // 用户取消
  }
}

const startModification = () => {
  taskStore.startModification()
}

const handleModificationClose = () => {
  taskStore.cancelModification()
}

const handleModificationConfirm = async (modification: TaskModificationType) => {
  try {
    const success = await taskStore.applyModification(modification)
    if (success) {
      uiStore.showSuccess('任务修改成功')
    } else {
      uiStore.showError('任务修改失败')
    }
  } catch (error) {
    console.error('Modification failed:', error)
    uiStore.showError('修改失败')
  }
}

// 监听执行状态变化
watch(() => taskStore.isExecuting, (executing) => {
  if (executing) {
    executionStartTime.value = new Date()
  } else {
    executionStartTime.value = null
  }
})

// 自动刷新
onMounted(() => {
  if (props.autoRefresh) {
    const refreshInterval = setInterval(() => {
      if (taskStore.isExecuting) {
        refreshTasks()
      }
    }, 5000)
    
    onUnmounted(() => {
      clearInterval(refreshInterval)
    })
  }
})
</script>

<style lang="scss" scoped>
.task-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--bg-color);
  border-left: 1px solid var(--border-color);
  
  &.task-panel--executing {
    .execution-controls {
      border-color: var(--primary-color);
    }
  }
  
  &.task-panel--empty {
    .panel-header {
      border-bottom: none;
    }
  }
}

// 面板头部
.panel-header {
  @include flex-between;
  padding: var(--spacing-md);
  border-bottom: 1px solid var(--border-color);
  background: var(--bg-color-light);
}

.header-left {
  @include flex-start;
  gap: var(--spacing-sm);
}

.panel-title {
  @include flex-start;
  gap: var(--spacing-xs);
  margin: 0;
  font-size: var(--font-size-medium);
  font-weight: 600;
  color: var(--text-color-primary);
}

.task-count-badge {
  :deep(.el-badge__content) {
    background: var(--primary-color);
  }
}

.header-actions {
  @include flex-center;
  gap: var(--spacing-xs);
}

.action-btn {
  width: 32px;
  height: 32px;
  
  &:hover {
    background: var(--bg-color-dark);
  }
}

// 任务统计
.task-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: var(--spacing-sm);
  padding: var(--spacing-md);
  background: var(--bg-color-light);
  border-bottom: 1px solid var(--border-color);
}

.stat-item {
  text-align: center;
  
  .stat-label {
    display: block;
    font-size: var(--font-size-extra-small);
    color: var(--text-color-secondary);
    margin-bottom: 2px;
  }
  
  .stat-value {
    display: block;
    font-size: var(--font-size-medium);
    font-weight: 600;
    
    &.pending {
      color: var(--task-pending-color);
    }
    
    &.progress {
      color: var(--task-progress-color);
    }
    
    &.completed {
      color: var(--task-success-color);
    }
  }
}

// 任务内容区域
.task-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.task-list-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

// 任务过滤器
.task-filters {
  @include flex-between;
  padding: var(--spacing-md);
  border-bottom: 1px solid var(--border-color);
  gap: var(--spacing-md);
}

.view-controls {
  flex-shrink: 0;
}

// 任务列表
.task-list {
  flex: 1;
  overflow-y: auto;
  @include scrollbar;
  
  &.task-list--list {
    .task-draggable {
      padding: 0 var(--spacing-sm);
    }
  }
  
  &.task-list--card {
    .task-draggable {
      padding: var(--spacing-md);
      display: grid;
      gap: var(--spacing-md);
    }
  }
}

.task-draggable {
  min-height: 100%;
}

// 任务操作栏
.task-actions {
  @include flex-between;
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--primary-color-lighter);
  border-top: 1px solid var(--primary-color);
}

.selected-info {
  font-size: var(--font-size-small);
  color: var(--primary-color);
  font-weight: 500;
}

.action-buttons {
  @include flex-center;
  gap: var(--spacing-xs);
}

// 空状态
.empty-state {
  flex: 1;
  @include flex-center;
  padding: var(--spacing-xl);
}

.empty-content {
  text-align: center;
  max-width: 300px;
}

.empty-icon {
  font-size: 64px;
  color: var(--text-color-placeholder);
  margin-bottom: var(--spacing-lg);
}

.empty-title {
  font-size: var(--font-size-large);
  color: var(--text-color-primary);
  margin-bottom: var(--spacing-sm);
}

.empty-description {
  font-size: var(--font-size-small);
  color: var(--text-color-secondary);
  line-height: 1.6;
  margin-bottom: var(--spacing-lg);
}

.empty-actions {
  @include flex-center;
}

// 执行控制区域
.execution-controls {
  border-top: 1px solid var(--border-color);
  background: var(--bg-color-light);
  padding: var(--spacing-md);
}

.control-buttons {
  @include flex-center;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-md);
  
  .execute-btn {
    flex: 1;
    
    &:hover {
      transform: translateY(-1px);
    }
  }
}

.execution-progress {
  .progress-info {
    @include flex-between;
    margin-bottom: var(--spacing-sm);
    font-size: var(--font-size-small);
    color: var(--text-color-secondary);
  }
  
  .progress-text {
    font-weight: 500;
  }
  
  .progress-time {
    font-family: monospace;
  }
}

// 响应式适配
@include respond-to(lg) {
  .task-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .task-filters {
    flex-direction: column;
    gap: var(--spacing-sm);
  }
  
  .panel-header {
    padding: var(--spacing-sm);
  }
  
  .execution-controls {
    padding: var(--spacing-sm);
  }
}

@include respond-to(md) {
  .task-stats {
    grid-template-columns: 1fr;
    gap: var(--spacing-xs);
  }
  
  .stat-item {
    @include flex-between;
    text-align: left;
    
    .stat-label,
    .stat-value {
      display: inline;
    }
  }
  
  .task-actions {
    flex-direction: column;
    gap: var(--spacing-sm);
    align-items: stretch;
    
    .action-buttons {
      justify-content: center;
    }
  }
  
  .control-buttons {
    flex-direction: column;
    
    .execute-btn {
      flex: none;
    }
  }
}

// 暗色主题
@include dark-theme {
  .task-panel {
    border-left-color: var(--border-color);
  }
  
  .panel-header,
  .task-stats,
  .execution-controls {
    background: var(--bg-color-dark);
  }
  
  .task-actions {
    background: rgba(64, 158, 255, 0.1);
  }
}
</style>